package de.backtomedieval.activities.gamemenu;

import java.util.ArrayList;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import de.backtomedieval.R;
import de.backtomedieval.activities.TopBar;
import de.backtomedieval.buildings.*;
import de.backtomedieval.main.Game;
import de.backtomedieval.error.BuildingAlreadyExitsException;
import de.backtomedieval.error.NotEnoughWaresException;
import de.backtomedieval.game.Costs;
import de.backtomedieval.game.Earning;
import de.backtomedieval.game.Helper;
import de.backtomedieval.game.KI;


public class Buildmenu extends Activity {
	
	private ListView lv1;
	private AbstractBuilding toBuild = null;
	private ArrayList<AbstractBuilding> m_buildings;
    private BuildingsAdapter m_buildingsadapter;
	private Handler mHandler = new Handler();
	private GridView grid_main;
	private boolean lastState = false;
	private TextView tv_buildinfo;
	private LinearLayout layoutChoose;
	private RelativeLayout layoutInfo;
	private int refresh = Game.getRefreshrate();
	private TextView title;
	private TopBar topbar;
	
	@Override
	public void onCreate(Bundle savedInstanceState)	{
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );
		setContentView(R.layout.buildmenu);
		
		
		tv_buildinfo = (TextView) findViewById(R.id.buildmenu_info_LabelBuildingInfo);
		layoutChoose = (LinearLayout)findViewById(R.id.LayoutBuildChoose);
		layoutInfo = (RelativeLayout)findViewById(R.id.LayoutBuildInfo);
		
		topbar = new TopBar(this);
		topbar.setTitle(Game.getGame().getcCity().getName() + ": " + getString(R.string.buildings));		
		Game.setLastActivity(this);
		
		lv1=(ListView)findViewById(R.id.ListViewBuild);
        m_buildings = new ArrayList<AbstractBuilding>();
        this.m_buildingsadapter = new BuildingsAdapter(this, R.layout.row, m_buildings);
       lv1.setAdapter(this.m_buildingsadapter);
       ArrayList<AbstractBuilding> u = Game.getGame().getcCity().getBuildings();
       for (int i=0; i<u.size(); i++) {
    	   m_buildingsadapter.add(u.get(i));
       }
       m_buildingsadapter.notifyDataSetChanged();
      
        lv1.setTextFilterEnabled(true);
 
        lv1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	onBuildListChoose(position);
            }
        });
             
		grid_main = (GridView)findViewById(R.id.GridViewMenu);
		grid_main.setAdapter(new ImageAdapter(this));
        grid_main.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	onBuildInfoMenuChoose(position);
            }
        });
        
	}
	
	
	public void changedCity() {
		title.setText(Game.getGame().getcCity().getName() + ": " + getString(R.string.buildings));
		m_buildingsadapter.clear();
        ArrayList<AbstractBuilding> u = Game.getGame().getcCity().getBuildings();
        for (int i=0; i<u.size(); i++) {
    	   m_buildingsadapter.add(u.get(i));
        }
        m_buildingsadapter.notifyDataSetChanged();
	}
	
	protected void onBuildInfoMenuChoose(int position) {
		if (toBuild != null) {
			if (position==0) {
				onButtonBuild();
			} else if (position==1) {
				toBuild.setActive(!toBuild.isActive(),Game.getGame().getcCity());
				switchToBuildingsList();
			}
		}
	}
	
	@Override
	public void onBackPressed() {
		RelativeLayout l1 =(RelativeLayout)findViewById(R.id.LayoutBuildInfo);
    	int vis = l1.getVisibility();
		if (vis == 0) {
			switchToBuildingsList();
		} else {
			mHandler.removeCallbacks(mUpdateTask);
			Intent changeToIntent = new Intent(this,Gamemenu.class);
			startActivity(changeToIntent);

			this.finish();
		}
		
		return;
	}

	protected void onButtonBuild() {
		if (toBuild != null) {
			try {
				Game.getGame().getcCity().buildOrUpgradeBuilding(toBuild);
				KI ki = Game.getGame().getPlayer().getKi();
				if (ki!=null) {
					ki.updateUpdateWares(toBuild);
				}
			} catch (BuildingAlreadyExitsException e) {
				Game.showPopup(this, toBuild.getName() + " is building or upgrading already.");
				switchToBuildingsList();
			} catch (NotEnoughWaresException e) {
				Game.showPopup(this, getString(R.string.notenoughwares) + "! " + toBuild.getName() + " "+ getString(R.string.wasnotbuild) + ".");
				switchToBuildingsList();
			}
		}
		switchToBuildingsList();
		m_buildingsadapter.notifyDataSetChanged();
	}

	private void switchToBuildingsList() {
		layoutInfo.setVisibility(8);
    	layoutChoose.setVisibility(0);
	}
	
	private void switchToBuildingInfo() {
		layoutChoose.setVisibility(8);
    	layoutInfo.setVisibility(0);
	}
	
	private class CreateBuildingInfoTask extends AsyncTask<Void, Void, String> {
	    /** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
		@Override
		protected String doInBackground(Void... params) {
			 return buildBuildingInfo();
		}
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    protected void onPostExecute(String result) {
	    	Log.v("Update", "Buildinfo");
	    	tv_buildinfo.setText(Html.fromHtml(result, imgGetter, null));
	    }
	}

	public String buildBuildingInfo() {
    	String info ="<Big><b>"+toBuild.getName()+"</b></Big> - ";
		Costs c = toBuild.getCosts();
		Earning e = toBuild.getEarn();
    	if (!toBuild.isBuilded()) {
			if (toBuild.getBuildCountdown() == 0) {
				info += "" + getString(R.string.notbuildedyet) +".<br><br>";
				if (c!=null) info += c.toString(1)+ "<br>";
				if (e!=null)  info += e.toString(1) + "<br>";
			} else {
				info += "" + getString(R.string.buildinprogress)+".<br><br>";
				if (c!=null) info += c.getSupplyString(1)+ "<br>";
				if (e!=null)  info += e.toString(1) + "<br>";
			}
		} else {
			info += "<b>Level " + toBuild.getLevel() +"</b><br><br>";
			info += "<b>" + getString(R.string.currentlevel) + "</b>:<br>";
			if (e!=null)  info += e.toString(toBuild.getLevel()) + "<br>";
			if (c!=null) {
				String tmp = c.getSupplyString(toBuild.getLevel());
				if (!tmp.equals(""))	info += c.getSupplyString(toBuild.getLevel()) + "<br>";
			}
			info +=  "<br><b>" + getString(R.string.nextlevel) +  "</b>:<br>";
			if (e!=null) info += e.toString(toBuild.getLevel()+1) +"<br>";
			if (c!=null) info += c.toString(toBuild.getLevel()+1);
			if (toBuild.getBuildCountdown() != 0) {
				info = info +"<br><br>" + getString(R.string.buildmenu_upgradetolevel) + " " + (toBuild.getLevel()+1) + " " + getString(R.string.inprogress) +  ".";
			}
		}
		return info;
	}
		
	protected void onBuildListChoose(int position) {
		if (position!=-1)
			toBuild = m_buildingsadapter.getItem(position);
		if (toBuild != null) {
			if (position!=-1) tv_buildinfo.setText("");
			if (position!=-1) switchToBuildingInfo();
			new CreateBuildingInfoTask().execute();
			if (position!=-1 || lastState != (toBuild.getBuildCountdown()==0)) {
				grid_main.setAdapter(new ImageAdapter(this));
			}
		} else {
		}		
	}
	
	
   ImageGetter imgGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
              Resources res = Buildmenu.this.getResources();
              Drawable drawable = res.getDrawable(Helper.getImageFromString(source));
              drawable.setBounds(0, 0, drawable.getIntrinsicWidth()/3, drawable.getIntrinsicHeight()/3);
              return drawable;
        }
    };
 
	
	
	private Runnable mUpdateTask = new Runnable() {
		   public void run() {
		       if (layoutChoose.getVisibility()==0) {
		    	   m_buildingsadapter.notifyDataSetChanged();
		    	   Log.v("Update", "Buildchooselist");
		       } else {
		    	   onBuildListChoose(-1);
		    	   Log.v("Update", "Building Info");
		       }
		       Log.v("Update", "Cityinfo");
		       topbar.refreshCityInfo();
		       mHandler.postDelayed(this,refresh);
		   }
	};
	
	private class BuildingsAdapter extends ArrayAdapter<AbstractBuilding> {

	    private ArrayList<AbstractBuilding> items;

	    public BuildingsAdapter(Context context, int textViewResourceId, ArrayList<AbstractBuilding> items) {
	            super(context, textViewResourceId, items);
	            this.items = items;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	            View v = convertView;
	            if (v == null) {
	                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                v = vi.inflate(R.layout.row, null);
	            }
	            AbstractBuilding o = items.get(position);
	            if (o != null) {
	                    TextView tt = (TextView) v.findViewById(R.id.toptext);
	                    TextView bt = (TextView) v.findViewById(R.id.bottomtext);
	                    ImageView icon=(ImageView)v.findViewById(R.id.icon);
	                     icon.setImageResource(o.getImage());
	                    if (tt != null) {
	                          tt.setText(o.getName());
	                    }
	                    if(bt != null){
	                    	if (o.isActive() && o.isBuilded()) {
	                    		bt.setTextColor(Color.WHITE);
	                    	} else if (!o.isBuilded()) {
	                    		bt.setTextColor(Color.WHITE);
	                    	} else {
	                    		bt.setTextColor(Color.RED);
	                    	}
	                    	if (o.isBuilded()) {
	                    		if (o.getBuildCountdown() == 0 ) {
	                    			bt.setText("Level "+ o.getLevel());
	                    		} else {
	                    			bt.setText("Level "+ o.getLevel() + " | Upgrading... "+ o.getBuildPercent());
	                    		}
	                    	} else {
	                    		if (o.getBuildCountdown() == 0 ) {
	                    			bt.setText(getString(R.string.notbuildedyet));
	                    		} else {
	                    			bt.setText(getString(R.string.buildinprogress) + "... " + o.getBuildPercent());
	                    		}
	                    	}
	                    }
	            }
	            return v;
	    }
	}
	
	
	public class ImageAdapter extends BaseAdapter{
		Context mContext;
		public static final int ACTIVITY_CREATE = 10;
		public ImageAdapter(Context c){
			mContext = c;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return 2;
		}


		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v;
			if(convertView==null){
				LayoutInflater li = getLayoutInflater();
				v = li.inflate(R.layout.gridiconlarge, null);
				TextView tv = (TextView)v.findViewById(R.id.icon_text);
				ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
				LinearLayout ll = (LinearLayout)v.findViewById(R.id.gridicon);
				if (toBuild!=null) {
					if(position ==0) {
						if(toBuild.getBuildCountdown()!=0) {
							ll.setVisibility(4);
							lastState=false;
						} else {
							ll.setVisibility(0);
							lastState=true;
						}
						if(toBuild.isBuilded()) {
							tv.setText(R.string.buildmenu_upgrade);
						} else {
							tv.setText(R.string.buildmenu_build);
						}
						
						iv.setImageResource(R.drawable.build);
					} else if(position ==1) {
						if(toBuild.isBuilded()) {
							ll.setVisibility(0);
						} else {
							ll.setVisibility(4);
						}
						
						
						if (toBuild.isActive()) {
							tv.setText(R.string.buildmenu_deactivate);
							iv.setImageResource(R.drawable.deactiv);
						} else {
							tv.setText(R.string.buildmenu_activate);
							iv.setImageResource(R.drawable.activ);
						}
						
					}
				}



			}
			else{
				v = convertView;
			}
			return v;
		}
		
		
		
		public Object getItem(int position) {
			return null;
		}
		
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
	}

	
	@Override
	public void onResume(){
	   super.onResume();
       mHandler.removeCallbacks(mUpdateTask);
       mHandler.postDelayed(mUpdateTask, 100);
	   Game.setLastActivity(this);
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public void onPause(){
	   super.onPause();
	   mHandler.removeCallbacks(mUpdateTask);
	}
	
}



